package
{
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.SharedObject;
	
	import mvc.AbstractView;
	import mvc.Controller;
	
	import mx.containers.Panel;
	import mx.containers.VBox;
	import mx.controls.Button;
	import mx.controls.ColorPicker;
	import mx.controls.ComboBox;
	import mx.controls.Label;
	import mx.controls.LinkButton;
	import mx.controls.List;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.controls.VideoDisplay;
	import mx.controls.textClasses.TextRange;
	import mx.events.ColorPickerEvent;
	import mx.events.ListEvent;
	
	public class splineChatView extends AbstractView
	{
		private var stage:Object;
		
		private var model:splineChatModel;
		private var mainPanel:Panel;
		private var logInPanel:Panel;
		private var serverIPLabel:Label;
		private var serverIPAddress:TextInput;
		private var userLabel:Label;
		private var userNameInput:TextInput; 
		
		private var logInButton:Button;
		
		
		private var ListProvider:Array;
		private var roomArray:Array;
		private var colorArray:Array;
		private var chatRoomPanel:Panel;
		private var chatRoomLabel:Label;
		private var chatRoomList:ComboBox;
		private var chatRoomEnterButton:Button;
		private var chatCreateRoomButton : Button;
		
		private var chatWindowPanel:Panel;
		private var chatWindow :TextArea;
		private var chatInput : TextArea;
		private var userListBox:VBox;
		private var userList:List;
		private var chatSendButton:Button;
		private var chatMyvideoButton:Button;
		private var chatDisconnectButton:Button;
		private var chatChangeRoomButton:Button;
		private var boldButton:LinkButton;
		private var italicsButton:LinkButton ;
		private var underlineButton:LinkButton;
		private var fontChooser:ComboBox;
		private var fontsizeChooser:ComboBox;
		private var fontColor:ColorPicker;
		private var selRange : TextRange;
		private var fontfamilyArray : Array;
		private var userpopPanelArray : Array;
		
		private var priMsgPanelX:Number=-300;
		private var priMsgPanelY:Number=0;
		
		private var nc:NetConnection;
		private var userName:String;
		private var user_so:SharedObject;
		private var clientID:String;
		public var tempPriPanel:Pri_msg_pnl;
		private var txtArea:TextArea;
		private var txtInput:TextInput;
		private var users:Object;
		
		
		public function splineChatView(stage:Object,m:splineChatModel,c:Controller,stageX:Number,stageY:Number,stageWidth:Number,stageHeight:Number)
		{
			super(m,c);
			this.stage=new Object;
			this.stage=stage;
			this.model=m;
			this.colorArray = ([0xedd3ad,0x80def5]);
			this.fontfamilyArray=(["Times New Roman","Roman","Garamond","Palatino","Helvetica",
									"Swiss","Impact","Script","Decorative","Blackletter","Fraktur",
									"Comic Sans","Modern","Courier","Calibri","Verdana","Frosty",
									"Georgia"]);
			this.roomArray=(["Physics", "Chemistry" ,"Maths"]);
			
			createLogInScreen();
		}
		
		private function createLogInScreen():void
		{
			mainPanel=new Panel;
			mainPanel.x=129;
			mainPanel.y=32;
			mainPanel.width=500;
			mainPanel.height=500;
			mainPanel.layout="absolute";
			this.stage.addChild(mainPanel);
			
			logInPanel=new Panel;
			logInPanel.x=0;
			logInPanel.y=0;
			logInPanel.title="LOG IN";
			logInPanel.width=295;
			logInPanel.height=270;
			logInPanel.alpha=0.5;
			logInPanel.layout="absolute";
			logInPanel.setStyle("backgroundColor","0x8e9395");
			mainPanel.addChild(logInPanel);
			
			serverIPLabel=new Label;
			serverIPLabel.x=10;
			serverIPLabel.y=20;
			serverIPLabel.text="Server IP";
			serverIPLabel.width=57;
			serverIPLabel.setStyle("color","0xffffff");
			logInPanel.addChild(serverIPLabel);
			
			serverIPAddress=new TextInput;
			serverIPAddress.x=92;
			serverIPAddress.y=18;
			serverIPAddress.toolTip="Enter the address of the server you want to connect";
			logInPanel.addChild(serverIPAddress);
			
			userLabel=new Label;
			userLabel.x=10;
			userLabel.y=72;
			userLabel.text="User Name";
			userLabel.width=68;
			userLabel.setStyle("color","0xffffff");
			logInPanel.addChild(userLabel);
			
			userNameInput=new TextInput;
			userNameInput.x=92;
			userNameInput.y=70;
			userNameInput.toolTip="Enter your name";
			logInPanel.addChild(userNameInput);
			
			logInButton=new Button;
			logInButton.x=76.5;
			logInButton.y=150;
			logInButton.width=112;
			logInButton.label="Log In";	
			logInPanel.addChild(logInButton);
			logInButton.addEventListener(MouseEvent.CLICK,onChatRoom);
			
		}
		
		private function onChatRoom(event:MouseEvent):void
		{
			this.userName=this.userNameInput.text;
			createChatRoom();
		}
		
		private function createChatRoom():void
		{
			this.mainPanel.removeAllChildren();
			this.chatRoomPanel=new Panel;
			this.chatRoomPanel.width=250;
			this.chatRoomPanel.x=this.mainPanel.width/2 - this.chatRoomPanel.width/2;
			this.chatRoomPanel.y=10;
			this.chatRoomPanel.layout="absolute";
			this.chatRoomPanel.height=400;
			this.chatRoomPanel.setStyle("borderAlpha",0.4);
			//this.setAttributes(this.chatRoomPanel);
			this.chatRoomPanel.title="Chat Rooms";
			this.mainPanel.addChild(this.chatRoomPanel);
			
			this.chatRoomLabel=new Label;
			chatRoomLabel.x=20;
			chatRoomLabel.y=20;
			chatRoomLabel.text="Room List";
			this.chatRoomPanel.addChild(this.chatRoomLabel);
			
			this.chatRoomList=new ComboBox;
			chatRoomList.x=20;
			chatRoomList.y=45;
			chatRoomList.width=160;
			chatRoomList.dataProvider=this.roomArray;
			this.chatRoomPanel.addChild(this.chatRoomList);
			
			this.chatRoomEnterButton=new Button;
			this.chatRoomEnterButton.x=20;
			this.chatRoomEnterButton.y=221;
			this.chatRoomEnterButton.label="Enter Room";
			this.chatRoomEnterButton.addEventListener(MouseEvent.CLICK,onEnterRoom);
			this.chatRoomPanel.addChild(this.chatRoomEnterButton);
			
			this.chatCreateRoomButton=new Button;
			this.chatCreateRoomButton.x=120;
			this.chatCreateRoomButton.y=221;
			this.chatCreateRoomButton.label="Create Room";
			//this.chatCreateRoomButton.addEventListener(MouseEvent.CLICK,createChatRoom);
			this.chatRoomPanel.addChild(this.chatCreateRoomButton);
		}
		
		private function onEnterRoom(event:MouseEvent):void
		{
			openChatDisplay();
		} 	
		
		private function openChatDisplay():void
		{
			this.mainPanel.removeAllChildren();
			
			this.nc=new NetConnection;
			//connection.objectEncoding = flash.net.ObjectEncoding.AMF0;
			nc.client=this;
			nc.addEventListener(NetStatusEvent.NET_STATUS , netStatus);
			nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, netError);
			nc.connect("rtmp://localhost/splineChat",userName,true,true,"user","Male","Room","world");
			
			
			this.chatWindowPanel=new Panel;
			chatWindowPanel.x=0;
			chatWindowPanel.y=0;
			chatWindowPanel.width=480;
			chatWindowPanel.height=460;
			chatWindowPanel.layout="absolute";
			chatWindowPanel.setStyle("backgroundColor",0xC1BBF6);
			chatWindowPanel.title="Chat Room Name";
			this.mainPanel.addChild(this.chatWindowPanel);
			
			this.chatChangeRoomButton=new Button;
			chatChangeRoomButton.x=106;
			chatChangeRoomButton.y=26 ;
			chatChangeRoomButton.label="Change Room";
			//chatChangeRoomButton.setStyle("fillColors",[0xF386F2,0xF386F2]);
			//chatChangeRoomButton.setStyle("fillAlphas",[.8,1]);
			this.chatWindowPanel.addChild(chatChangeRoomButton);
			
			this.chatSendButton=new Button;
			chatSendButton.x=371;
			chatSendButton.y=350;
			chatSendButton.width=79;
			chatSendButton.height=60;
			chatSendButton.label="Send";
			//chatChangeRoomButton.setStyle("fillColors",[0xF386F2,0xF386F2]);
			//chatChangeRoomButton.setStyle("fillAlphas",[.8,1]);
			this.chatWindowPanel.addChild(chatSendButton);
			this.chatSendButton.addEventListener(MouseEvent.CLICK,sendPublicMessagefrmBut)
			
			this.chatMyvideoButton=new Button;
			chatMyvideoButton.x=12;
			chatMyvideoButton.y=26;
			chatMyvideoButton.label="My Video";
			//chatMyvideoButton.setStyle("fillColors",[0xF386F2,0xF386F2]);
			//chatMyvideoButton.setStyle("fillAlphas",[.8,1]);
			this.chatMyvideoButton.addEventListener(MouseEvent.CLICK, openMyCam);
			this.chatWindowPanel.addChild(chatMyvideoButton);
			
			this.chatDisconnectButton=new Button;
			chatDisconnectButton.x=222;
			chatDisconnectButton.y=26;
			chatDisconnectButton.label="Disconnect";
			//chatDisconnectButton.setStyle("fillColors",[0xF386F2,0xF386F2]);
			//chatDisconnectButton.setStyle("fillAlphas",[.8,1]);
			this.chatWindowPanel.addChild(chatDisconnectButton);
			
			this.chatWindow=new TextArea; 
			chatWindow.x=10;
			chatWindow.y=68;
			chatWindow.width=353;
			chatWindow.height=242;
			chatWindow.editable=false;
			this.chatWindowPanel.addChild(chatWindow);
			
			this.chatInput=new TextArea;
			
			chatInput.x=10;
			chatInput.y=350;
			chatInput.width=353;
			chatInput.height=60;
			this.chatWindowPanel.addChild(chatInput);
			this.chatInput.addEventListener(KeyboardEvent.KEY_DOWN , sendPublicMessage);
			
			
			this.userListBox=new VBox;
			userListBox.x=371;
			userListBox.y=68;
			userListBox.width=79;
			userListBox.height=242;
			this.chatWindowPanel.addChild(userListBox);
			
			this.ListProvider=new Array;
			
			//this.ListProvider=(["akshay"]);
			//this.ListProvider.push(this.userNameInput.text);
			
			this.userpopPanelArray=new Array;
			
			this.userList=new List;
			userList.x=0;
			userList.y=0;
			userList.width=this.userListBox.width;
			userList.height=this.userListBox.height;
			userList.dataProvider=this.ListProvider;
			userList.setStyle("alternatingItemColors",colorArray);
			this.userList.addEventListener(ListEvent.ITEM_CLICK,openMenu);
			userListBox.addChild(userList);
			
			
			
			this.selRange = new TextRange(this.chatInput,true); 
			
			this.boldButton=new LinkButton;
			boldButton.x=15;
			boldButton.y=320;
			boldButton.width=30;
			boldButton.height=22;
			boldButton.setStyle("fontWeight","bold");
			boldButton.setStyle("fontSize",15);
			boldButton.label="B";
			boldButton.toggle=true;
			boldButton.selected=false;
			boldButton.addEventListener(MouseEvent.CLICK,changefontWeight);
			this.chatWindowPanel.addChild(this.boldButton);
			
			this.italicsButton=new LinkButton;
			italicsButton.x=55;
			italicsButton.y=320;
			italicsButton.width=30;
			italicsButton.height=22;
			italicsButton.setStyle("fontStyle","italic");
			italicsButton.setStyle("fontSize",15);
			italicsButton.label="I";
			italicsButton.toggle=true;
			italicsButton.selected=false;
			italicsButton.addEventListener(MouseEvent.CLICK,changefontItalic);
			this.chatWindowPanel.addChild(this.italicsButton);
			
			this.underlineButton=new LinkButton;
			underlineButton.x=95;
			underlineButton.y=320;
			underlineButton.width=30;
			underlineButton.height=22;
			underlineButton.setStyle("textDecoration","underline");
			underlineButton.setStyle("fontSize",15);
			underlineButton.label="U";
			underlineButton.toggle=true;
			underlineButton.selected=false;
			underlineButton.addEventListener(MouseEvent.CLICK,changefontUnderline);
			this.chatWindowPanel.addChild(this.underlineButton);
			
			this.fontChooser=new ComboBox;
			fontChooser.dataProvider=this.fontfamilyArray;
			fontChooser.x=135;
			fontChooser.y=320;
			fontChooser.width=100;
			fontChooser.height=22;
			fontChooser.addEventListener(ListEvent.CHANGE,changefontFamily);
			this.chatWindowPanel.addChild(this.fontChooser);
			
			this.fontColor=new ColorPicker;
			fontColor.x=245;
			fontColor.y=320;
			fontColor.addEventListener(ColorPickerEvent.CHANGE,changefontColor);
			this.chatWindowPanel.addChild(this.fontColor);
			
			setNumberOfUsersConnected();
		}
		
		private function openMenu(event:ListEvent):void
		{
			var isExist:Boolean=new Boolean;
			isExist=false;
			
			for each( var tempPnl:Pri_msg_pnl in this.userpopPanelArray)
			{
				if(tempPnl.title==this.userList.selectedItem.toString())
				{
					isExist=true;
					//jo karna hai yahi karna hai..
				}
			}
			
			if(!isExist)
			{
				this.priMsgPanelX+=300;
				

				var usrpnl:Pri_msg_pnl=new Pri_msg_pnl();
				usrpnl.x=this.stage.width-300-this.priMsgPanelX;
				usrpnl.y=this.stage.height-320;
				usrpnl.title=this.userList.selectedItem.toString();
				//this.chatWindowPanel.addChild(usrpnl);
				this.userpopPanelArray.push(usrpnl);
				displayPrivateMessagePanel();
			}
			
		}
		
		private function displayPrivateMessagePanel():void
		{
			tempPriPanel =new Pri_msg_pnl();
			tempPriPanel =this.userpopPanelArray.pop();
			this.stage.addChild(tempPriPanel);
			this.userpopPanelArray.push(tempPriPanel);
			tempPriPanel.txtInput.addEventListener(KeyboardEvent.KEY_DOWN,sendPrivateMessage);
			
		}
		
		private function changefontWeight(event:MouseEvent):void{
			
			
			if(this.boldButton.selected)
			{
				if(this.chatInput.selectionEndIndex!=this.chatInput.selectionBeginIndex)
				{
					
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.fontWeight="bold";
					this.chatInput.setFocus();
					
				}
				this.chatInput.htmlText+='<b>';
				this.boldButton.setStyle("fontWeight","normal");
				this.chatInput.setFocus();
			}
			else{
				if(this.chatInput.selectionEndIndex !=this.chatInput.selectionBeginIndex)
				{
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.fontWeight="normal";
					this.chatInput.setFocus();
					
				}
				this.chatInput.htmlText+='</b>';
				this.boldButton.setStyle("fontWeight","bold");
				this.chatInput.setFocus();
			}
		}
		
		
		private function changefontItalic(event:MouseEvent):void{
			
			if(this.italicsButton.selected)
			{
				if(this.chatInput.selectionEndIndex!=this.chatInput.selectionBeginIndex)
				{
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.fontStyle="italic";
					this.chatInput.setFocus();
					
				}
				
				this.chatInput.htmlText+='<i>';
				this.italicsButton.setStyle("fontStyle","normal");
				this.chatInput.setFocus();
			}
			else{
				if(this.chatInput.selectionEndIndex !=this.chatInput.selectionBeginIndex)
				{
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.fontStyle="normal";
					this.chatInput.setFocus();
					
				}
				this.chatInput.htmlText+='</i>';
				this.italicsButton.setStyle("fontStyle","italic");
				this.chatInput.setFocus();
			}
		
		}
		
		private function changefontUnderline(event:MouseEvent):void{
			
			if(this.underlineButton.selected)
			{
				if(this.chatInput.selectionEndIndex!=this.chatInput.selectionBeginIndex)
				{
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.textDecoration="underline";
					this.chatInput.setFocus();
					
				}
				
				this.chatInput.htmlText+='<u>';
				this.underlineButton.setStyle("textDecoration","normal");
				this.chatInput.setFocus();
			}
			else{
				if(this.chatInput.selectionEndIndex !=this.chatInput.selectionBeginIndex)
				{
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.textDecoration="normal";
					this.chatInput.setFocus();
					
				}
				this.chatInput.htmlText+='</u>';
				this.underlineButton.setStyle("textDecoration","underline");
				this.chatInput.setFocus();
			}

		}
		
		
		private function changefontFamily(event:ListEvent):void{
			trace(this.fontChooser.selectedLabel);
			var str:String;
			str = new String;
			str='"'+this.fontChooser.selectedLabel+'"';
			if(this.chatInput.selectionEndIndex!=this.chatInput.selectionBeginIndex)
				{
					
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					trace(this.selRange.text);
					this.selRange.fontFamily=this.fontChooser.selectedLabel;
					this.chatInput.setFocus();
					
				}
				this.chatInput.htmlText+='<font face='+str+'>';
				this.chatInput.setFocus();
			
			
		}
		
		private function changefontColor(event:ColorPickerEvent):void{
			
			var str:String;
			str='"'+'#'+this.fontColor.selectedColor.toString(16)+'"';
			
				if(this.chatInput.selectionEndIndex!=this.chatInput.selectionBeginIndex)
				{
					
					
					this.selRange.beginIndex=this.chatInput.selectionBeginIndex;
					this.selRange.endIndex=this.chatInput.selectionEndIndex;
					this.selRange.color='0x'+this.fontColor.selectedColor.toString(16);
					this.chatInput.setFocus();
					
				}
				
				this.chatInput.htmlText+='<font color='+str+'>';
				trace(this.chatInput.htmlText+='<font color='+str+'>');
				this.chatInput.setFocus();
				
		}
		
		private function openMyCam(event:MouseEvent):void
		{
			var myCamPanel:Panel=new Panel();
			myCamPanel.x=this.mainPanel.x+this.mainPanel.width;
			myCamPanel.y=mainPanel.y;
			myCamPanel.width=250;
			myCamPanel.height=300;
			this.stage.addChild(myCamPanel);
			
			var myCamDisplay:VideoDisplay=new VideoDisplay();
			myCamDisplay.x=0;
			myCamDisplay.y=0;
			myCamDisplay.width=213;
			myCamDisplay.height=265;
			myCamPanel.addChild(myCamDisplay);
			
			var video:Video=new Video();
			video.width=myCamDisplay.width;
			video.height=myCamDisplay.height;
			myCamDisplay.addChild(video);
			
			var cam:Camera=new Camera();
			cam=Camera.getCamera(null);
			cam.setMode(213,265,75,true);
			if(cam)
				video.attachCamera(cam);
		}
		
		private function netError(event:SecurityErrorEvent):void {
			trace("netSecurityError: " + event);
		}
		
		private function netStatus(event:NetStatusEvent):void {
			trace("netStatus: " + event);
			var info:Object = event.info;
			trace(info.code);
			if (info.code == "NetConnection.Connect.Success") {
				trace("connected");
				syncClients();
				this.updateUsersList();
			}
		}
		
		private function syncClients():void
		{
			user_so = SharedObject.getRemote("user_so", nc.uri, true);
			user_so.client = this;
			user_so.connect(nc);
			//user_so.send("getClientName");
		}
		
		public function setId(clientID:String):void
		{
			this.clientID = clientID;	
			trace(clientID);		
		}
		
		private function sendPublicMessagefrmBut(event:MouseEvent):void
		{
			//trace("sending to all"+this.chatInput.text);
			nc.call("send_public",null,this.userName,this.chatInput.htmlText);
		}
		
		private function sendPublicMessage(event:KeyboardEvent):void
		{
			if(event.charCode==13)
			{
				//trace("sending to all "+this.chatInput.text);
				nc.call("send_public",null,this.userName,this.chatInput.htmlText);
				this.chatInput.text="";
			}
		}
		
		public function receivePublicMsg(userName:String,message:String):void
		{
			//trace("message recieved = "+userName+" : "+message);
			this.chatWindow.htmlText+=userName+" : "+message;
			this.chatInput.text="";
		}
		
		public function updateUsersList():void
		{
			trace("calling get users list");
			var responder:Responder=new Responder(getUsersList,null);
			nc.call("getUserList",responder);
		}
		
		public function getUsersList(_users):void
		{
			this.users=_users;
			var _user:Object=new Object;
			for( _user in _users)
			{
				//trace("pseudo:"+users[_user].pseudo+" webcam:"+users[_user].webcam+"  ID = "+users[_user].id);
				this.ListProvider.push(users[_user].pseudo);
				this.userList.dataProvider=this.ListProvider;
			}
			
			//this.ListProvider=users;
		}
		
		private function sendPrivateMessage(event:KeyboardEvent):void
		{
			var _user:Object=new Object;
			if(event.charCode==13)
			{
				for(_user in users)
				{
					if(users[_user].pseudo==this.tempPriPanel.title)
					{
						nc.call("send_private",null,this.userName,users[_user].id,this.tempPriPanel.txtInput.text);
						trace("sending private message to "+users[_user].pseudo);
						this.tempPriPanel.txtArea.text+=this.userName+" : "+this.tempPriPanel.txtInput.text;
						this.tempPriPanel.txtInput.text="";
						
					}
				}
			}
		}
		
		public function receivePrivateMsg(from:String,message:String):void
		{
			var isExist:Boolean=false;
			for each( var tempPnl:Pri_msg_pnl in this.userpopPanelArray)
			{
				if(tempPnl.title==from)
				{
					isExist=true;
					tempPnl.txtArea.text+=from+" : "+message+"\n";
				}
			}
			
			if(!isExist)
			{
				this.priMsgPanelX+=300;
				

				var usrpnl:Pri_msg_pnl=new Pri_msg_pnl();
				usrpnl.x=this.stage.width-300-this.priMsgPanelX;
				usrpnl.y=this.stage.height-320;
				usrpnl.title=from;
				//this.chatWindowPanel.addChild(usrpnl);
				usrpnl.txtInput.addEventListener(KeyboardEvent.KEY_DOWN,sendPrivateMessage);
				this.userpopPanelArray.push(usrpnl);
				displayPrivateMessagePanel();
				usrpnl.txtArea.text+=from+" : "+message+"\n";
			}
			
			//trace("message recieved = "+message);
		}
		
		private function setNumberOfUsersConnected():void
		{
			var responder:Responder=new Responder(getNumberOfUsers,null);
			nc.call("getNumberUsersConnected",responder);
		}
		
		public function getNumberOfUsers(obj):void
		{
			//trace("users = "+obj);
		}
		
		public function newUserJoined(name:String):void
		{
			this.ListProvider.push(name);
			this.userList.dataProvider=this.ListProvider;
		}
	}
}